package com.booksystem.campuslibrarymanagementsystem.controller.user;


import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Renewalapprovalrequest.DeletBorrowRenew;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Renewalapprovalrequest.Renewalapproval;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Renewalapprovalrequest.RenewalapprovalList;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Renewalapprovalrequest.Renewalist;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.commen.result.userresuilt.RenewalTable;
import com.booksystem.campuslibrarymanagementsystem.entity.RenewalapprovalTable;
import com.booksystem.campuslibrarymanagementsystem.service.RenewalapprovalTableService;
import com.booksystem.campuslibrarymanagementsystem.utils.JwtUtil;
import com.booksystem.campuslibrarymanagementsystem.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@RequestMapping("/User")
@Api(tags = "图书续借")
@RestController
public class BookRenewController {



    /*图书续借
    1，输入账户id，图书id
    2，续借原因
    3，续借时间，续借过期时间
    4，审核状态默认为未通过
     */
    @Autowired
    RenewalapprovalTableService renewalapprovalTableService;
    @PostMapping("/bookRenew")
    @ApiOperation(value = "图书续借",notes = "通过账户id，图书id进行续借图书")
    public Result BookRenew (@RequestBody Renewalapproval renewalapproval){
        Map<String, Object> parsed =JwtUtil.tokenPre(renewalapproval.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int bookid =renewalapproval.getBookid();//图书id
                String  reason = renewalapproval.getCause();//续借原因
                String time = TimeUtil.getTime();//自动生成当前借阅时间
                // 判断账户id
                if ((reason == null || reason.trim().isEmpty() ) ) {
                    return Result.fail("续借原因不能为空");
                }
                // 检查该用户是否已经续借了这本书，并且续借状态为“已通过”
                List<RenewalapprovalTable> existingBorrow = renewalapprovalTableService.existsByAccountAndBookidi((String) account, bookid);
                if (existingBorrow != null && !existingBorrow.isEmpty()) {
                    for (RenewalapprovalTable entry : existingBorrow) {
                        if ("已通过".equals(entry.getApprovalstate())) {//已通过,检查续借记录是否已经过期
                            // 检查续借记录是否已经过期
                            if (entry.getExpirationdate().isBefore(LocalDate.now())) {//续借时间大于过期时间
                                // 如果续借记录已经过期，允许再次续借
                                break; // 退出循环
                            } else {
                                // 如果续借记录还未过期，不允许再次续借
                                return Result.fail(String.format("您已经续借过这本书：%s", bookid));
                            }
                        }
                    }
                }
                // 计算过期时间
                LocalDate borrowTime = LocalDate.now();
                LocalDate expirationDate = borrowTime.plus(30, ChronoUnit.DAYS); // 假设续借期限是30天

                RenewalapprovalTable hh = new RenewalapprovalTable();
                hh.setBookid(bookid);
                hh.setRenewdate(time);
                hh.setExpirationdate(expirationDate);
                hh.setApprovalstate("未审批");
                hh.setCause(reason);
                hh.setAccount((String) account);
                int c =renewalapprovalTableService.add(hh);
                if(c>0){
                    return Result.success("续借成功，过期时间为：" + expirationDate,1);
                }
                return Result.fail("续借失败");

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }



    /*
    查看列表
   通过判断状态（未通过，通过）
   可以查看所有未通过的列表和所有通过列表
    */
    @PostMapping("/listtstatus")
    @ApiOperation(value = "是否通过，已拒绝图书续借列表", notes = "可以查看所有未通过的列表和所有通过的续借图书列表")
    public Result<List<RenewalTable>> selectstatuslist (@RequestBody RenewalapprovalList renewalapprovalList) {
        Map<String, Object> parsed = JwtUtil.tokenPre(renewalapprovalList.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                String statu = renewalapprovalList.getApprovalstate();
                // 判断状态是否为空
                if (statu == null || statu.trim().isEmpty()) {
                    List<RenewalTable>  aa = renewalapprovalTableService.selectByaccount((String) account);
                    if (aa.isEmpty()) {
                        // 提供更具体的错误信息，说明是基于哪几个条件没有找到匹配的图书
                        return Result.fail(String.format("没有找到基于账户id：%s", (String) account));
                    } else {
                        return Result.success(aa, 1);
                    }
                }

                List<RenewalTable> statusList =null;
                if ("已通过".equals(statu)) {
                    statusList = renewalapprovalTableService.liststatus((String) account, statu);

                } else if ("未通过".equals(statu)) {
                    statusList = renewalapprovalTableService.liststatus((String) account, statu);
                } else if ("未审批".equals(statu)) {
                    statusList = renewalapprovalTableService.liststatus((String) account, statu);
                }else {
                    return Result.fail("无效的状态值");
                }
                // 检查列表是否为空
                if (statusList.isEmpty()) {
                    return Result.fail("没有找到账户id为 '" +(String) account + "状态为 '"+ statu + "' 的续借记录");
                } else {
                    return Result.success(statusList, statusList.size());
                }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }



    @PostMapping("/bookRenewlist")
    @ApiOperation(value = "查看所有续借记录",notes = "账户id，进行查看自己的所有续借列表")
    public Result<List<RenewalTable>> borrowList(@RequestBody Renewalist renewalist) {
        Map<String, Object> parsed = JwtUtil.tokenPre(renewalist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                List<RenewalTable>  aa = renewalapprovalTableService.selectByaccount((String) account);
                if (aa.isEmpty()) {
                    // 提供更具体的错误信息，说明是基于哪几个条件没有找到匹配的图书
                    return Result.fail(String.format("该账户id没有进行续借图书：%s", (String) account));
                } else {
                    return Result.success(aa, 1);
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

    @PostMapping("/deleteBookRenew")
    @ApiOperation(value = "删除续借书籍",notes = "账户id，续借id进行删除该账户下该图书的续借记录")
    public Result deleteBookRenew(@RequestBody DeletBorrowRenew deletBorrowRenew) {
        Map<String, Object> parsed = JwtUtil.tokenPre(deletBorrowRenew.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int  bookid =deletBorrowRenew.getApprovalid();  //续借id
                int hh = renewalapprovalTableService.deleteByAccountAndBookid((String) account, bookid);
                // 首先检查该用户是否已经续借了这本书
                if (hh>0) {
                    return  Result.success("成功删除该图书续借记录",1);
                }
                return Result.fail(String.format("没有该图书的续借记录：%s", bookid));
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }


}




